package door.smartlift.top.common.utils;

/**
 * Created by wsll789 on 2017/2/13.
 */

import door.smartlift.top.exception.MyDefineException;
import org.apache.http.Consts;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpRequest {
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param url
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static JSONObject sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();

            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return new JSONObject(result);
    }



    public  static Map executeGET(HttpHost httpProxy, String uri, Map<String,String> map) throws IOException, MyDefineException {
        Map hashMap=new HashMap();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Map.Entry<String,String> entry:map.entrySet()){
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        uri=uri+"?"+ URLEncodedUtils.format(params, HTTP.UTF_8);
        HttpGet httpGet = new HttpGet(uri);
        httpGet.addHeader("Content-Type", "application/json");
        HttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        response = (CloseableHttpResponse) client.execute(httpGet);
        Integer code= response.getStatusLine().getStatusCode();
        String responseContent = EntityUtils.toString(response.getEntity(), Charset.forName("utf-8"));
        hashMap.put("code",code);
        hashMap.put("data",responseContent);
        return  hashMap;
    }






    public  static Map executeJsonPost(  String uri, Map map) throws IOException, MyDefineException {
        Map hashMap=new HashMap();
        HttpPost httpPost = new HttpPost(uri);
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
        httpPost.addHeader("Accept", "application/json; charset=utf-8");
        HttpClient client = HttpClients.createDefault();
        if (map != null) {
            String postEntity= JsonUtil.map2json(map);
            StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
            httpPost.setEntity(entity);
        }
        CloseableHttpResponse response = null;
        response = (CloseableHttpResponse) client.execute(httpPost);
        Integer code= response.getStatusLine().getStatusCode();
        String responseContent = EntityUtils.toString(response.getEntity(), Charset.forName("utf-8"));
        hashMap.put("code",code);
        hashMap.put("data",responseContent);
        return  hashMap;
    }









}
